package com.tao.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tao.cart.mapper.CartMapper;
import com.tao.cart.service.CartService;
import com.tao.clients.ProductClient;
import com.tao.param.CartSaveParam;
import com.tao.param.ProductCollectParam;
import com.tao.param.ProductIdParam;
import com.tao.pojo.Cart;
import com.tao.pojo.Product;
import com.tao.utils.R;
import com.tao.vo.CartVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 86130
 * 购物车业务实现类
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {


    @Resource
    private ProductClient productClient;

    @Resource
    private CartMapper cartMapper;

    /**
     * 购物车数据添加方法
     *
     * @param cartSaveParam
     * @return 001 成功    002 已经存在    003 没有库存
     */
    @Override
    public R save(CartSaveParam cartSaveParam) {
        //查询商品数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cartSaveParam.getProductId());
        Product product = productClient.productDetail(productIdParam);
        if (product == null) {
            return R.fail("商品已经删除，无法添加！");
        }
        //检查库存
        if (product.getProductNum() == 0) {
            R ok = R.ok("没有库存了");
            ok.setCode("003");
            log.info("CartServiceImpl.save业务结束，结果：{}",ok);
            return ok;
        }

        //检查是否已经添加
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", cartSaveParam.getUserId());
        cartQueryWrapper.eq("product_id", cartSaveParam.getProductId());

        Cart cart = cartMapper.selectOne(cartQueryWrapper);
        if (cart != null) {
            //证明购物车里有了,原有数量+1
            cart.setNum(cart.getNum() + 1);
            cartMapper.updateById(cart);
            R ok = R.ok("购物车里有该商品了，数量+1");
            ok.setCode("002");
            log.info("CartServiceImpl.save业务结束，结果：{}",ok);
            return ok;
        }

        //添加购物车
        cart = new Cart();
        cart.setNum(1);
        cart.setUserId(cartSaveParam.getUserId());
        cart.setProductId(cartSaveParam.getProductId());
        int rows = cartMapper.insert(cart);
        log.info("CartServiceImpl.save业务结束，结果：{}",rows);
        //结果封装返回
        CartVo cartVo = new CartVo(product, cart);

        return R.ok("购物车数据添加成功！",cartVo);
    }

    /**
     * 返回购物车数据
     *
     * @param userId
     * @return 返回数组
     */
    @Override
    public R list(Integer userId) {

        //用户id，查询购物车数据
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", userId);
        List<Cart> carts = cartMapper.selectList(cartQueryWrapper);

        //判断是否存在，不存在，返回空集合
        if (carts == null || carts.size() == 0) {
            carts = new ArrayList<>();
            return R.ok("购物车空空如也", carts);
        }

        //存在，获取商品id集合，并调用商品服务查询
        ArrayList<Integer> productIds = new ArrayList<>();
        for (Cart cart : carts) {
            productIds.add(cart.getProductId());
        }
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        List<Product> productList = productClient.cartList(productCollectParam);

        //进行vo封装
        Map<Integer, Product> productMap = productList.stream().collect(Collectors.toMap(Product::getProductId, v -> v));
        ArrayList<CartVo> cartVoList = new ArrayList<>();
        for (Cart cart : carts) {
            CartVo cartVo = new CartVo(productMap.get(cart.getProductId()), cart);
            cartVoList.add(cartVo);
        }
        R r = R.ok("数据库数据查询成功", cartVoList);
        log.info("CartServiceImpl.list业务结束，结果：{}",r);
        return r;
    }

    /**
     * 更新购物车业务
     *
     * @param cart
     * @return
     */
    @Override
    public R update(Cart cart) {
        //查询商品数据
        ProductIdParam productIdParam = new ProductIdParam();
        productIdParam.setProductID(cart.getProductId());
        Product product = productClient.productDetail(productIdParam);

        //判断库存是否可用
        if (cart.getNum()>product.getProductNum()) {
            log.info("CartServiceImpl.update业务结束，结果：{}","修改失败，库存不足");
            return R.fail("修改失败，库存不足");
        }

        //修改数据库
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", cart.getUserId());
        cartQueryWrapper.eq("product_id", cart.getProductId());
        Cart newCart = cartMapper.selectOne(cartQueryWrapper);

        newCart.setNum(cart.getNum());
        int rows = cartMapper.updateById(newCart);
        log.info("CartServiceImpl.update业务结束，结果：{}",rows);
        return R.ok("修改购物车数量成功");
    }

    /**
     * 删除购物车业务
     *
     * @param cart
     * @return
     */
    @Override
    public R remove(Cart cart) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", cart.getUserId());
        cartQueryWrapper.eq("product_id", cart.getProductId());

        int rows = cartMapper.delete(cartQueryWrapper);
        log.info("CartServiceImpl.update业务结束，结果：{}",rows);

        return R.ok("删除购物车信息成功！");
    }

    /**
     * 清空对应id的购物车项
     *
     * @param cartIds
     */
    @Override
    public void clearIds(List<Integer> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
        log.info("CartServiceImpl.clearIds业务结束，结果：{}",cartIds);
    }

    /**
     * 查询购物车项
     *
     * @param productId
     * @return
     */
    @Override
    public R check(Integer productId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        Long count = cartMapper.selectCount(queryWrapper);
        if (count > 0) {
            return R.fail("有：" + count + "个=件购物车视频引用,删除失败");
        }
        return R.ok("购物车无商品引用");
    }
}
